from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from django.core.exceptions import ValidationError
from .models import Userinfo, Userintroduce
from useradmin.models import Usermanagement
from book.models import Booktitle
import json
@csrf_exempt
@require_POST
def add_user(request):

    # 解析请求数据
    try:
        data = json.loads(request.body.decode('utf-8'))
    except json.JSONDecodeError:
        return JsonResponse({'error': 'Invalid JSON'}, status=400)

    # 提取数据
    name = data.get('name')
    age = data.get('age')
    email = data.get('email')
    introduce = data.get('introduce')
    # grade = data.get('grade')
    # score = data.get('score')
    password = data.get('password')
    # control = data.get('control')

    # 验证数据（可以根据需要自定义验证逻辑）
    if not name or not age or not email:
        return JsonResponse({'error': '信息不完整'}, status=400)

    # 创建 Userinfo 实例并保存
    try:
        userinfo = Userinfo.objects.create(
            name=name,
            age=age,
            email=email
        )
    except ValidationError as e:
        return JsonResponse({'error': str(e)}, status=400)

    # 创建 Userintroduce 实例并保存
    try:
        userintroduce = Userintroduce.objects.create(
            introduce=introduce,
            # grade=grade,
            # score=score,
            user=userinfo
        )
    except ValidationError as e:
        return JsonResponse({'error': str(e)}, status=400)

    # 创建 Usermanagement 实例并保存
    try:
        usermanagement = Usermanagement.objects.create(
            password=password,
            # control=control,
            user=userinfo
        )
    except ValidationError as e:
        return JsonResponse({'error': str(e)}, status=400)

    # 返回成功响应
    return JsonResponse({'status': 'success', 'user_id': userinfo.id}, status=201)


@csrf_exempt
@require_POST
# 获取指定用户传递id----uuid

def get_user_by_id(request):
    # 解析请求数据
    try:
        print(request)
        data = json.loads(request.body.decode('utf-8'))
    except json.JSONDecodeError:
        return JsonResponse({'error': '无效'}, status=400)

    # 从请求数据中获取用户ID
    user_id = data.get('id')

    if not user_id:
        return JsonResponse({'error': 'id无效'}, status=400)

    try:
        # 查找用户信息
        user = Userinfo.objects.get(uuid=user_id)
    except Userinfo.DoesNotExist:
        return JsonResponse({'error': '没有用户'}, status=404)

    # 获取当前用户的 Userintroduce 和 Usermanagement 实例
    userintroduce = Userintroduce.objects.filter(user=user).first()
    usermanagement = Usermanagement.objects.filter(user=user).first()
    # 这个获取多个，安装上面的写就是只有一个
    userbook = Booktitle.objects.filter(author=user)

    # 组装用户数据
    user_info = {
        'id': user.id,
        'name': user.name,
        'age': user.age,
        'email': user.email,
        'pub_time': user.pub_time.isoformat(),
        'is_active': user.is_active,
        'introduce': userintroduce.introduce if userintroduce else None,
        'grade': userintroduce.grade if userintroduce else None,
        'portrait': userintroduce.portrait.url if userintroduce and userintroduce.portrait else None,
        'score': userintroduce.score if userintroduce else None,
        'password': usermanagement.password if usermanagement else None,
        'control': usermanagement.control if usermanagement else None,
        # 循环获取关联创作的图书多个返回数组
        'books': [{'name': book.name, 'bookUuid': str(book.bookUuid)} for book in userbook]  # 添加所有图书信息
    }

    # 返回 JSON 响应
    return JsonResponse({'user': user_info}, safe=False)